using Microsoft.EntityFrameworkCore;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Infrastructure.Persistence.Repositories;

public class GameRepository : IGameRepository
{
    private readonly GameDbContext _context;

    public GameRepository(GameDbContext context)
    {
        _context = context;
    }

    public async Task<Game?> GetByIdAsync(Guid id)
    {
        return await _context.Games
            .Include(g => g.Room)
            .Include(g => g.Room.Players)
            .FirstOrDefaultAsync(g => g.Id == id);
    }

    public async Task<Game?> GetByRoomIdAsync(Guid roomId)
    {
        return await _context.Games
            .Include(g => g.Room)
            .Include(g => g.Room.Players)
            .FirstOrDefaultAsync(g => g.Room.Id == roomId);
    }

    public async Task<Game> AddAsync(Game game)
    {
        _context.Games.Add(game);
        await _context.SaveChangesAsync();
        return game;
    }

    public async Task<Game> UpdateAsync(Game game)
    {
        _context.Games.Update(game);
        await _context.SaveChangesAsync();
        return game;
    }

    public async Task DeleteAsync(Guid id)
    {
        var game = await _context.Games.FindAsync(id);
        if (game != null)
        {
            _context.Games.Remove(game);
            await _context.SaveChangesAsync();
        }
    }

    public async Task<IEnumerable<Game>> GetActiveGamesAsync()
    {
        return await _context.Games
            .Include(g => g.Room)
            .Include(g => g.Room.Players)
            .Where(g => g.Room.Status == GameStatus.Playing)
            .ToListAsync();
    }
}
